#include "RingQueue.hpp"
#include<cstdio>
#include<ctime>
#include<unistd.h>

class Task 
{
private:
    int _cnt;
public:
    Task(){}
    Task(int cnt):_cnt(cnt){}
    int Run()
    {
        int sum=0;
        for(int i=1;i<=_cnt;i++)
            sum+=i;
        return sum;
    }
    void Show()
    {
        printf("Thread:%p is running...Task done: counting from 1 to %d",pthread_self(),_cnt);
    }
};
void* consumer(void* c)
{
    RingQueue<Task>* rq=(RingQueue<Task>*)c;
    while(true)
    { 
        //取出数据+计算结果
        Task t;
        rq->Get(&t);
        int ret=t.Run();
        std::cout<<"consumer->";
        t.Show();
        printf(" ret=%d\n",ret);
        sleep(1);
    }
    return nullptr;
}

void* producter(void* p)
{
    srand((unsigned)time(nullptr));
    RingQueue<Task>* rq=(RingQueue<Task>*) p;
    while(true)
    {
        //生成数据和放入数据
        int t=rand()%100+1;
        rq->Put(Task(t));
        std::cout<<"producter->Thread:"<<pthread_self()<<" is running...Task made: count from 1 to "<<t<<std::endl;
        //sleep(1);
    }
    return nullptr;
}
int main()
{
    RingQueue<int>* rq=new RingQueue<int>(NUM);
    pthread_t cid1,cid2,cid3,cid4,pid1,pid2;
    pthread_create(&cid1,nullptr,consumer,(void*)rq);
    pthread_create(&cid2,nullptr,consumer,(void*)rq);
    pthread_create(&cid3,nullptr,consumer,(void*)rq);
    pthread_create(&cid4,nullptr,consumer,(void*)rq);
    pthread_create(&pid1,nullptr,producter,(void*)rq);
    pthread_create(&pid2,nullptr,producter,(void*)rq);

    pthread_join(cid1,nullptr);
    pthread_join(cid2,nullptr);
    pthread_join(cid3,nullptr);
    pthread_join(cid4,nullptr);
    pthread_join(pid1,nullptr);
    pthread_join(pid2,nullptr);
    delete rq;
}
